package com.miao.util.mail;

import com.miao.util.basic.Config;
import com.miao.util.basic.ExcutorUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * Created by miao on 2015/4/10.
 */
public class MailUtils {
    private static MailUtils instance;
    private static String host = "smtp.163.com";

    private static String acc = "merle_miao@163.com";

    private static String accName = "merle_miao";

    private static String password = "a37868153";
    private static Logger logger = Logger.getLogger(MailUtils.class);
    private PopupAuthenticator au;

    public static MailUtils getInstance() {
        String host = Config.getLocalProperty("mail.host");
        if (StringUtils.isNotBlank(host)) {
            host = host;
        }
        String acc = Config.getLocalProperty("mail.acc");
        if (StringUtils.isNotBlank(acc)) {
            acc = acc;
        }
        String accName = Config.getLocalProperty("mail.accName");
        if (StringUtils.isNotBlank(accName)) {
            accName = accName;
        }
        String password = Config.getLocalProperty("mail.password");
        if (StringUtils.isNotBlank(password)) {
            password = password;
        }
        return SingletonHolder.instance;
    }

    public static void main(String[] args) {
        MailUtils mailUtils = getInstance();
//        mailUtils.sendMail("miaosk@yugusoft.com", "453673382@qq.com", "hi", "hello");
//        mailUtils.sendMail("miaosk@yugusoft.com", "hi", "hellox");
        mailUtils.sendMail(new String[]{"miaosk@yugusoft.com"}, null, "测试邮件", "这是带有附件的测试邮件", new File[]{new File("F:/utils.jar")});
    }

    public void sendMail(String[] to, String[] copyTo, String subject, String body, File[] files) {
        this.au = new PopupAuthenticator(accName, password);
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, this.au);
        session.setDebug(true);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(acc));
            Address[] tos = null;
            if (to != null) {
                tos = new InternetAddress[to.length];
                for (int i = 0; i < to.length; i++) {
                    tos[i] = new InternetAddress(to[i]);
                }
            }
            Address[] cos = null;
            if (copyTo != null) {
                cos = new InternetAddress[copyTo.length];
                for (int i = 0; i < copyTo.length; i++) {
                    cos[i] = new InternetAddress(copyTo[i]);
                }
            }
            msg.setRecipients(Message.RecipientType.TO, tos);
            msg.setRecipients(Message.RecipientType.CC, cos);
            msg.setHeader("X-Mailer", "LOTONtechEmail");
            msg.setSubject(subject);
            Multipart mp = new MimeMultipart();
            BodyPart mdp = new MimeBodyPart();
            mdp.setContent(body, "text/html;charset=UTF-8");
            mp.addBodyPart(mdp);
            if ((files != null) && (files.length > 0)) {
                for (File file : files) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(MimeUtility.encodeText(file.getName()));
                    mp.addBodyPart(mbp);
                }
            }
            msg.setContent(mp);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
        }
    }

    public void asyncSendMail(final String to, final String copyTo, final String subject, final String body) {
        ExcutorUtil excutorUtil = ExcutorUtil.getSingleInstance();
        excutorUtil.execute(new Runnable() {
            public void run() {
                MailUtils.this.sendMail(to, copyTo, subject, body);
            }
        });
    }

    public void asyncSendMail(final String to, final String subject, final String body) {
        ExcutorUtil excutorUtil = ExcutorUtil.getSingleInstance();
        excutorUtil.execute(new Runnable() {
            public void run() {
                MailUtils.this.sendMail(to, subject, body);
            }
        });
    }

    public void sendMail(String to, String copyTo, String subject, String body) {
        sendMail(new String[]{to}, new String[]{copyTo}, subject, body, null);
    }

    public void sendMail(String to, String subject, String body) {
        sendMail(new String[]{to}, null, subject, body, null);
    }

    static class SingletonHolder {
        static MailUtils instance = new MailUtils();
    }

    private class PopupAuthenticator extends Authenticator {
        String username = null;
        String password = null;

        public PopupAuthenticator(String user, String pass) {
            this.username = user;
            this.password = pass;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            System.out.println(this.username + this.password);
            return new PasswordAuthentication(this.username, this.password);
        }
    }

}
